package service;

import mapper.BrandMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import pagination.PageBean;
import pojo.Brand;
import utils.SqlSessionFactoryUtils;

import java.util.List;

public class BrandService {
    public List<Brand>selectAll(){

        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession=factory.openSession();

        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        List<Brand> brandList = brandMapper.selectAll();
        sqlSession.close();
        return brandList;
    }

    public void add(Brand brand){
        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession=factory.openSession();

        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        brandMapper.add(brand);
        sqlSession.commit();
        sqlSession.close();
    }

    public Brand selectById(int id){

        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession=factory.openSession();

        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        Brand brand= brandMapper.selectById(id);

        sqlSession.close();
        return brand;
    }

    public void update(Brand brand){
        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession=factory.openSession();

        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        brandMapper.update(brand);
        sqlSession.commit();
        sqlSession.close();
    }
    public void delete(int id){
        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession=factory.openSession();

        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        mapper.deleteById(id);

        sqlSession.commit();

        sqlSession.close();
    }
    public PageBean<Brand> selectAllPage(int currentPage, int pageSize){

        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession=factory.openSession();

        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        PageBean<Brand>pageBean=new PageBean<Brand>();

        int beginIndex = (currentPage -1 ) * pageSize;
        List<Brand> brandList = brandMapper.selectAllPage(beginIndex ,pageSize);

        int totalCount = brandMapper.selectCount();

        pageBean.setData(brandList);
        pageBean.setCurrentPage(currentPage);
        pageBean.setPageSize(pageSize);
        pageBean.setTotalCount(totalCount);

        int totalPage = (int) (Math.ceil( totalCount*1.0/pageSize ));
        pageBean.setTotalPage(totalPage);

        sqlSession.close();
        return pageBean;
    }
}
